﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using OneDrive.Model;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

namespace OneDrive.DataAccess
{
    class SyncHouseInfo
    {
        const string strAjkUrl = "https://xa.anjuke.com/sale/p#page-rd1/?kw=#keyword#filtersort";

        private List<HouseInfo> houseInfos = new List<HouseInfo>();

        private List<HouseExtInfo> houseExtInfos = new List<HouseExtInfo>();

        private List<AgentInfo> agentInfos = new List<AgentInfo>();

        private List<CommunityInfo> communityInfos = new List<CommunityInfo>();

        public void GetHouseInfoList(int Index, string strKeyWord)
        {
            string url = strAjkUrl.Replace("#page", Index.ToString()).Replace("#keyword", strKeyWord);
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            Stream resStream = wc.OpenRead(url);
            StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
            string strWebContent = sr.ReadToEnd();
            resStream.Close();
            wc.Dispose();
            //(?<= (data - company\=\\"\\"\stitle\=\\"))[^\\]+

            //WebProxy proxyObject = new WebProxy(IP, port);//这里我是用的代理。
            //向指定地址发送请求
            //HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url);
            ////HttpWReq.Proxy = proxyObject;
            //HttpWReq.Timeout = 10000;
            //HttpWReq.Accept = "*/*";
            //HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
            //StreamReader sr = new StreamReader(HttpWResp.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
            ////注意上面的编码了吗？？
            //HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            //doc.Load(sr);
            //int res = CheckIsGoodProxy(doc); //这是我解析的函数，还没到那一步。不解释了。
            //sr.Close();
            //HttpWResp.Close();
            //HttpWReq.Abort();


            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(strWebContent);
            string xpathDiv = "//li[@class='list-item']";//找到class=zg_itemImmersion的div节点
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(xpathDiv);
            foreach(HtmlNode node in nodes)
            {
                HouseInfo house = new HouseInfo();
                HouseExtInfo houseExt = new HouseExtInfo();
                AgentInfo agent = new AgentInfo();
                CommunityInfo community = new CommunityInfo();

                // 1.获取HouseInfo HouseExtInfo
                HtmlNode nodeTittle = node.SelectSingleNode(".//div[@class='house-title']");
                house.Tittle = nodeTittle.InnerText.Trim();     //发布标题
                string strHouseDetailUrl = nodeTittle.ChildNodes[1].Attributes["href"].Value;
                Regex regHid = new Regex("(?<=(prop\\/view\\/A))\\w+");
                Match matchHid = regHid.Match(strHouseDetailUrl);
                house.HouseID = int.Parse(matchHid.Groups[0].Value);       //房屋ID

                GetSingleHouseInfo(strHouseDetailUrl,ref house,ref houseExt);

                HtmlNode nodeDetails = node.SelectSingleNode(".//div[@class='details-item']");
                house.HouseHold = nodeDetails.ChildNodes[1].InnerText.Trim();                               //户型
                house.BuiltupArea = float.Parse(nodeDetails.ChildNodes[3].InnerText.Replace("m²", ""));     //面积
                house.Floor = nodeDetails.ChildNodes[5].InnerText;                                          //楼层
                house.TotalPrice = float.Parse(node.SelectSingleNode(".//span[@class='price-det']").InnerText.Replace("万", "")); //总价

                // 2.获取AgentInfo

                houseInfos.Add(house);
                houseExtInfos.Add(houseExt);
            }

        }

        /// <summary>
        /// 获取单个房屋的详细信息
        /// </summary>
        /// <param name="strUrl">房屋的Url</param>
        /// <param name="hInfo">房屋基本信息</param>
        /// <param name="hExtInfo">房屋扩展信息</param>
        public void GetSingleHouseInfo(string strUrl, ref HouseInfo hInfo, ref HouseExtInfo hExtInfo)
        {
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            Stream resStream = wc.OpenRead(strUrl);
            StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
            string strWebContent = sr.ReadToEnd();
            resStream.Close();
            wc.Dispose();
            // 2.load
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(strWebContent);
            // 3.prase HouseInfo
            HtmlNode nodeHouseInfoBox = doc.DocumentNode.SelectSingleNode("//div[@class='houseInfoBox']");
            string strEncode = nodeHouseInfoBox.SelectSingleNode("//span[@class='house-encode']").InnerText;
            string strReleaseDate = strEncode.Substring(strEncode.LastIndexOf("：") + 1);
            hInfo.ReleaseTime = DateTime.Parse(strReleaseDate);     //发布时间

            HtmlNodeCollection nodesDetail = nodeHouseInfoBox.SelectNodes("//div[@class='houseInfo-content']");

            string strCommunityUrl = nodesDetail[0].ChildNodes[1].Attributes["href"].Value;
            Regex regCid = new Regex("(?<=community\\/view\\/)\\d+");
            Match matchCid = regCid.Match(strWebContent);
            hInfo.CommunityID = int.Parse(matchCid.Groups[0].Value);    //小区ID
            hInfo.Orientation = nodesDetail[7].InnerText;               //朝向
            hInfo.Type = nodesDetail[9].InnerText;                      //房屋类型
            hInfo.Floor = nodesDetail[10].InnerText;                    //楼层
            hInfo.Decorate = nodesDetail[11].InnerText;                 //装修程度
            hInfo.Limit = nodesDetail[12].InnerText;                    //房本年限
            hInfo.OnlyHouse = (nodesDetail[13].InnerText == "是") ? 1 : 0;   //是否唯一

            HtmlNode nodeAgent = doc.DocumentNode.SelectSingleNode("//div[@class='broker-tagdiv clearfix']");
            Regex regAid = new Regex("(?<=gongsi-jjr-)\\d+");
            Match matchAid = regAid.Match(nodeAgent.InnerHtml);
            if(matchAid.Groups.Count >0)
            {
                if(matchAid.Groups[0].Value.Length != 0)
                {
                    hInfo.AgentID = int.Parse(matchAid.Groups[0].Value);        //经纪人ID
                }
            }

            // 4.parse HouseExtInfo ("//div[starts-with(@class,'content_single')]")
            HtmlNodeCollection nodesExtInfo = doc.DocumentNode.SelectNodes("//div[@class='houseInfo-item']");

            hExtInfo.SellingPoint = nodesExtInfo[0].ChildNodes[3].InnerText.Trim();
            hExtInfo.SellingReason = nodesExtInfo[1].ChildNodes[3].InnerText.Trim();
            hExtInfo.HouseID = hInfo.HouseID;
        }

        private void GetSingleAgentInfo()
        {

        }
    }
}
